package com.xxwy.lifecycle.definition;

import com.xxwy.lifecycle.bean.User;
import com.xxwy.lifecycle.bean.Users;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * .
 *
 * @author xxwy
 * @date 2021/7/13 0013
 */
@Configuration
public class BeanDefinitionOverridingTest {

//    @Bean
//    public User user() {
//        return new User("XX", 1);
//    }
//
    /**
     * bean name写一样，只注册了一个。不针对直接调用registerBeanDefinition方法
     * @return
     */
    @Bean("xx")
    public User user2() {
        return new User("XX", 2);
    }

    /**
     * bean name写一样，只注册了一个。
     * @return
     */
    @Bean("xx")
    public Users users() {
        return new Users("XX", 2);
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(BeanDefinitionOverridingTest.class);
        applicationContext.refresh();
        // debug:
        // beanDefinitionRegistry
        BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        definitionBuilder.addPropertyValue("age","11")
                .addPropertyValue("name","register");
        applicationContext.registerBeanDefinition("xx", definitionBuilder.getBeanDefinition());

        DefaultListableBeanFactory listableBeanFactory = applicationContext.getDefaultListableBeanFactory();
        Map<String, User> userMap = listableBeanFactory.getBeansOfType(User.class);
        Map<String, Users> usersMap = listableBeanFactory.getBeansOfType(Users.class);
        System.out.println(userMap.size());
        System.out.println(usersMap.size());

        applicationContext.close();
    }
}
